<template>
  <div id="news" class="app-container">
    <!-- <div class=" white-bg pagination-container "> -->
    <list-search-bar
      ref="searchbar"
      :search-rule="searchRule"
      @submit="getList($event, pageInfo)"
      @add="showEdit()"
      @update:value="searchData = $event"
      style="padding-left:12px"
    >
      <!-- <template slot="btn-group-right" slot-scope="{ row }">
          <el-button size="mini" type="warning" @click="importE"
            >导入</el-button
          >
          <el-button
            size="mini"
            type="primary"
            v-if="exportShow"
            @click="exportAll"
            >导出</el-button
          >
        </template> -->
    </list-search-bar>
    <list-table
      :showEdit="true"
      @edit="showEdit($event)"
      @remove="remove"
      :showRemove="true"
      v-loading="listLoading"
      :listRule="editRule"
      :listData="listData"
      btnGroupWidth="280px"
      :tableHeight="tableHeight - 70"
    >
      <template slot="btn-group" slot-scope="{ row }">
        <!-- <el-button
          size="mini"
          @click="fabu(row)"
          :type="row.zhuangtai == '' ? 'primary' : ''"
          :disabled="row.zhuangtai == '' ? false : true"
          >发布</el-button
        > -->
        <!-- <el-button size="mini" @click="showEdit(row, true)">查看</el-button> -->
        <el-button
          size="mini"
          @click="shenhe(row)"
          :type="row.isVerify == '未审核' ? 'warning' : ''"
          :disabled="row.isVerify == '未审核' ? false : true"
          >审核</el-button
        >
      </template>
    </list-table>
    <pagination
      :page-sizes="[20]"
      :page-size="pageInfo.size"
      :current-page="pageInfo.page"
      :isFixed="false"
      :marginTop="true"
      :total="pageInfo.total"
      @pagination="getList(searchData, { ...pageInfo, page: $event.page })"
    />
    <!-- </div> -->

    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="65%"
      :visible.sync="editDialog"
      v-loading="editLoading"
      v-dialogDrag
      custom-class="widget-dialog widget-form widget-search center no-margin color-white black-bg2"
      title="填写信息"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <el-button size="mini" @click="reset">重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  knowledgeListAll as searchApi, //获取列表的api
  knowledgeInsert as insertApi, //更新、新增数据的api
  knowledgeUpdate as updateApi, //更新、新增数据的api
  knowledgeDelete as removeApi, //删除数据的api
  knowledgeVerifyKnowledge, //审核知识库
  knowledgeGetLanmuByMenuId as getTypeApi, //获取列表的api
  knowledgeGetById //查询莫个知识库
} from "@/api";

import { editRule, searchRule } from "@/formRules/ListRules";
import { editFormOptions, getData } from "@/formRules";
import cloneDeep from "lodash/cloneDeep";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import mixin from "@/mixins/tableAutoHeight";
import { mapState } from "vuex";
import { xlsxExport } from "@/utils/csv";
export default {
  mixins: [mixin],
  name: "WikiList",
  configurations: {
    title: "列表",
    isDefault: true,
    show: true
  },
  components: {},
  data() {
    return {
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {
        type: [5]
      }, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      pageInfo: {
        page: 1,
        size: 20,
        total: 0
      },
      exportData: [],
      exportShow: false,
      fieldList: [],
      isLook: false,
      typeList: [],
      hasColumn: false,
      permissionList: [] //权限列表
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  mounted() {
    let column = ["AffairsOpen", "FinanceOpen"];
    column.forEach(e => {
      if (this.routerPath.indexOf(e) > -1) {
        this.hasColumn = true;
        this.editRule = editRule(true);
      }
    });
    this.getType();
    this.getList(this.searchData, this.pageInfo);
  },
  computed: {
    routerPath() {
      return this.$route.path;
    },
    layoutName() {
      return this.$route?.meta?.layout || "";
    },
    menuId() {
      if (!this.menuList?.length) return "";
      return this.menuList.find(e => e.layout == this.layoutName)?.parent;
    },
    ...mapState(["isAdmin", "userNow", "user"]),
    menuList() {
      return this.user?.menuList;
    },
    userId() {
      return this.userNow?.id;
    },
    userName() {
      return this.userNow?.userName;
    },
    queryName() {
      return this.$route?.query?.userName || "";
    },
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    }
  },
  methods: {
    async getType() {
      let { data } = await getTypeApi({
        menuId: this.menuId
      });
      this.typeList = data.map(e => {
        return {
          value: e.id,
          label: e.categoryName
        };
      });
    },
    toData(data) {
      let result = "";
      if (data && data.length) {
        result = data[data.length - 1];
      } else {
        result = data;
      }
      return result;
    },
    /**
     * @name 查询全部数据
     */
    getExportData(query) {
      this.exportShow = false;
      let params = {
        ...query,
        page: 1,
        menuId: this.menuId,
        size: this.pageInfo.total
      };
      params.categoryId = this.toData(params.categoryId);
      params.sysUser = this.queryName ? this.queryName : this.userName;
      searchApi(params)
        .then(res => {
          this.exportData = res.data.list;
          this.exportShow = true;
        })
        .finally(() => {
          //   this.exportShow = false;
        });
    },
    initType(data) {
      this.searchData.categoryId = data.id;
      this.$nextTick(() => {
        this.getList(this.searchData, this.pageInfo);
      });
    },
    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括size和page
     * @description 调用成功则刷新listData
     */
    async getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query,
        menuId: this.menuId
      };
      queryParam.categoryId = this.toData(queryParam.categoryId);
      queryParam.sysUser = this.queryName ? this.queryName : this.userName;
      let { data, code, msg } = await searchApi(queryParam).finally(() => {
        this.listLoading = false;
      });
      if (code == 200) {
        this.listData = data.list;
        delete data.list;
        Object.assign(this.pageInfo, data);
        this.getExportData(query);
      } else {
        this.$notified.error({
          message: msg
        });
      }
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row, isLook) {
      this.isLook = isLook || false;
      if (!row) {
        // if (this.fieldList.length) {
        //   this.fieldList.forEach(e => {
        //     this.editFormInstance.removeField(e.id);
        //   });
        // }
        this.editRule = editRule(this.hasColumn);
        this.$nextTick(() => {
          this.editData = getData(editRule(this.hasColumn));
          //   this.editData.categoryId = this.searchData.categoryId;
          this.editData.allContent = "";
          this.editDialog = true;
          this.setcategoryId();
        });
      } else {
        this.editData.allContent = "";
        this.getDetail(row.id);
      }
    },
    setcategoryId() {
      this.$nextTick(() => {
        this.editFormInstance.updateRule("categoryId", {
          options: this.typeList
        });
      });
    },
    async getDetail(id) {
      //先去除之前选中的
      if (this.fieldList.length) {
        this.fieldList.forEach(e => {
          this.editFormInstance.removeField(e.id);
        });
      }

      let { data } = await knowledgeGetById({ id: id });
      this.fieldList = data.fieldList;
      this.editData = cloneDeep(data);
      this.editData.fieldList = data.fieldList;
      this.editDialog = true;
      this.setcategoryId();
      let isTitle = false;
      data.fieldList.forEach(e => {
        //动态插入
        if (e.keyTitle == "内容") {
          isTitle = true;
        }
        this.$nextTick(() => {
          this.editFormInstance.append({
            type: e.keyTitle == "内容" ? "FormWangEditor" : "FormWangEditor",
            title: e.keyTitle,
            field: e.id.toString(),
            value: e.keyValue
          });
        });
      });
      if (!isTitle) {
        setTimeout(() => {
          this.editFormInstance.append({
            type: "FormWangEditor",
            title: "内容",
            field: "allContent",
            value: ""
          });
        }, 600);
      } else {
        setTimeout(() => {
          this.editFormInstance.removeField("allContent");
        }, 600);
      }
      //   if (this.isLook) {
      //     this.editRule.forEach((e, index) => {
      //       e.props.disabled = true;
      //       this.$set(this.editRule, index, e);
      //     });
      //   } else {
      //     this.editRule.forEach((e, index) => {
      //       e.props.disabled = false;
      //       this.$set(this.editRule, index, e);
      //     });
      //   }
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    async update(editData) {
      if (!this.validation()) return;
      if (editData.allContent) {
        //内容先默认写死一个
        if (!editData.fieldList?.length) {
          editData.fieldList.push({
            keyTitle: "内容",
            keyValue: editData.allContent,
            type: 0
          });
        }
      }
      for (let key in editData) {
        if (Number(key)) {
          //确定是传过来的值
          editData.fieldList.forEach(e => {
            delete e.fieldName;
            if (e.id == Number(key)) {
              e.keyValue = editData[key];
            }
          });
          delete editData[key];
        }
      }
      console.log("editData-----");
      console.log(editData);
      //   return;
      editData.categoryId = this.toData(editData.categoryId);
      //   return false;
      //   this.editLoading = true;
      editData.menuId = this.menuId;
      if (editData.id) {
        this.editLoading = true;

        let { data, code, msg } = await updateApi(editData).finally(
          () => (this.editLoading = false)
        );
        if (code == 200) {
          this.$notified.success({
            message: "更新数据成功"
          });
          this.getList(this.searchData, this.pageInfo);
          this.editDialog = false;
        } else {
          this.$notified.error({
            message: msg
          });
        }
      } else {
        this.editLoading = true;

        let { data, code, msg } = await insertApi(editData).finally(
          () => (this.editLoading = false)
        );
        if (code == 200) {
          this.$notified.success({
            message: "新增数据成功"
          });
          this.getList(this.searchData, this.pageInfo);
          this.editDialog = false;
        } else {
          this.$notified.error({
            message: msg
          });
        }
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      return true;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    remove(row) {
      this.$confirm("确认删除当前" + row + "分类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          removeApi({ id: row.id, userId: this.userId })
            .then(() => {
              this.$notified.success({
                message: "删除成功"
              });
              this.getList(this.searchData, this.pageInfo);
            })
            .finally(() => {
              this.listLoading = false;
            });
        })
        .catch(() => {
          this.$notified({
            message: "已取消删除"
          });
        });
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    },
    async shenhe(row) {
      this.$confirm("确认通过当前审核?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          knowledgeVerifyKnowledge({ id: row.id, userId: this.userId }).then(
            ({ data, code, msg }) => {
              if (code == 200) {
                this.$notified.success({
                  message: "审核已通过"
                });
                this.getList(this.searchData, this.pageInfo);
              } else {
                this.$notified.error({
                  message: msg
                });
              }
            }
          );
        })
        .catch(() => {
          this.$notified({
            message: "已取消审核通过"
          });
        });
    },
    importE() {
      this.$notified.normal({
        message: "当前功能待开发中..."
      });
    },
    exportAll() {
      let ruleHeadList = editRule()
        .filter(i => i.tableVisible)
        .map(i => i.title);

      let dataArray = this.exportData.map(
        ({
          content,
          categoryName,
          keyWord,
          introduction,
          isVerify,
          createTime
        }) => {
          return [
            content,
            categoryName,
            keyWord,
            introduction,
            isVerify,
            createTime
            // allContent
          ];
        }
      );
      xlsxExport("知识库列表.xlsx", ruleHeadList, dataArray);
    },
    fabu(row) {
      this.$confirm("确认发布当前知识库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 	let id1 = this.listData.findIndex(arr => arr.id == row.id);
          // this.$set(this.listData, id1, editData);
          this.listData.forEach(e => {
            if (e.id == row.id) {
              e.zhuangtai = "1";
            }
          });
          this.$notified.success({
            message: "知识库已通过发布"
          });
        })
        .catch(() => {
          this.$notified({
            message: "已取消发布"
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
#idName {
  position: relative;
  overflow: hidden;
}
</style>
